package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.entity.remote.VideoDetailResult;
import com.showsu.editor.entity.remote.WhoseCardVideoDetailResp;
import com.showsu.editor.entity.remote.batmkeyPrivate.DyAwemeDetailResult2;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListData;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListResp;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: 接口平台 https://www.batmkey.cn/user/
 * @Date: Created in 8:27 下午 2023/6/19
 * @Modified By:
 */
@Slf4j
@Component
public class BatmkeyUtil {

    @Value("${batmkey.urlV3}")
    private String urlV3;

    @Value("${batmkey.token}")
    private String token;
    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 6;

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情，这个接口带实况图信息
     * https://www.batmkey.cn/doc_detail/156/
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        params.put("param", "noteid=" + noteId);
        params.put("router", "/xiaohongshu/note/raw");
        Type type = new TypeToken<AwemeDetailPlatformResult>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer).create();
        log.info("Batmkey查询xhs笔记详情-请求参数noteId:{}", noteId);
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    String responseInner = HttpUtil.post(urlV3, JsonUtil.toJson(params), Constant.defaultTimeOut);
                    log.info("Batmkey查询xhs笔记详情-响应耗时:{}", System.currentTimeMillis() - start);
                    AwemeDetailPlatformResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            &&  CollectionUtils.isEmpty(temp.getData())
                            && (temp.getStatus_code() != null && temp.getStatus_code().intValue() == 0)) {
                        return Constant.xhsAwemeNotExist0;
                    }

                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.get_msg()))
                                || (!CollectionUtils.isEmpty(temp.getData())
                                    && temp.getData().get(0) != null
                                    && !CollectionUtils.isEmpty(temp.getData().get(0).getNote_list())
                                    && Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().get(0).getNote_list().get(0).getText()))
                                    )
                                )
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist0;
                    }
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getStatus_code() != null && temp.getStatus_code().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("BatmkeyUtil.getXhsAwemeDetail(String) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist0)) {
            return null;
        }
        try {
            AwemeDetailPlatformResult awemeDetailResult = gson.fromJson(response, type);
            result.setData(awemeDetailResult);
        } catch (Exception e) {
            log.error("BatmkeyUtil.getXhsAwemeDetail(String) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }

    /**
     * 获取xhs笔记评论数据（带live）
     * @param noteId
     * @param cursor 首页传空，翻页是用上一页的最后一个评论id
     * @param interfaceId
     * @return
     */
    public TikhubXhsAwemeCommentListResp getXhsAwemeCommentList(String noteId, String cursor, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        params.put("param", "note_id=" + noteId + "&start=" + cursor);
        params.put("router", "/xhs/note/comment");

        TikhubXhsAwemeCommentListResp result = new TikhubXhsAwemeCommentListResp();
        Type type = new TypeToken<TikhubXhsAwemeCommentListData>(){}.getType();
        Gson gson = new Gson();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    String responseInner = HttpUtil.post(urlV3, JsonUtil.toJson(params), Constant.defaultTimeOut);
                    log.info("BatmkeyUtil查询xhs作品评论数据-响应耗时:{}, noteId:{}, cursor:{}", System.currentTimeMillis() - start, noteId, cursor);
                    TikhubXhsAwemeCommentListData temp = gson.fromJson(responseInner, type);
                    //如果平台那边报错再重试一次
                    if (temp != null && temp.getStatus_code() != null && temp.getStatus_code().intValue() != 0) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("BatmkeyUtil.getXhsAwemeCommentList(String,String,Long) error, noteId:{}, cursor:{}, e:{}", noteId, cursor, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId, new StringBuilder("noteId=").append(noteId).append(",cursor=").append(cursor).toString());
            return result;
        }
        try {
            TikhubXhsAwemeCommentListData tikhubXhsAwemeCommentListData = gson.fromJson(response, type);
            tikhubXhsAwemeCommentListData.initVideoInfo();
            //这个接口要把最后一条评论的id作为下一页请求的start
            if (tikhubXhsAwemeCommentListData.getData() != null && ! CollectionUtils.isEmpty(tikhubXhsAwemeCommentListData.getData().getComments())) {
                tikhubXhsAwemeCommentListData.getData().setCursor(
                        tikhubXhsAwemeCommentListData.getData().getComments().get(
                                tikhubXhsAwemeCommentListData.getData().getComments().size() - 1
                        ).getId());
            }
            result.setData(tikhubXhsAwemeCommentListData);
        } catch (Exception e) {
            log.error("BatmkeyUtil.getXhsAwemeCommentList(String,String,Long) convert error, noteId:{}, cursor:{}, e:{}", noteId, cursor, e);
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", "9a11dc4908d411eeb952fa163ede3646114d80c9dd11a9");
        params.put("param", "noteid=66b479c8000000001e01e1ae");
        params.put("router", "/xiaohongshu/note/raw");
        String response = HttpUtil.post("http://api.batmkey.cn:8000/api/v3", JsonUtil.toJson(params), Constant.defaultTimeOut);
        System.out.println(response);
    }
}
